package com.sdkj.fixed.asset.hc.service;

import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.hc.vo.in.ConsumeParams;
import com.sdkj.fixed.asset.api.hc.vo.in.MablesParams;
import com.sdkj.fixed.asset.api.hc.vo.in.StockParams;
import com.sdkj.fixed.asset.api.hc.vo.out.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.hc.mapper.CategoryMapper;
import com.sdkj.fixed.asset.hc.mapper.CategoryProductMapper;
import com.sdkj.fixed.asset.hc.mapper.OrgManagementMapper;
import com.sdkj.fixed.asset.hc.mapper.UserDataAuthMapper;
import com.sdkj.fixed.asset.pojo.hc.Category;
import com.sdkj.fixed.asset.pojo.hc.CategoryProduct;
import com.sdkj.fixed.asset.pojo.system.UserDateAuth;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/***
 *
 * @author scx
 *
 */
@Service
public class CategoryService extends BaseService<Category> {

    @Resource
    private CategoryMapper mapper;

    @Resource
    private OrgManagementMapper orgMapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Resource
    private UserDataAuthMapper userDateAuthMapper;

    @Override
    public BaseMapper<Category> getMapper() {
        return mapper;
    }

    /**
     * 校验code
     *
     * @param entity 仓库
     * @param flag   新增/修改
     */
    private void checkCode(Category entity, Boolean flag) {
        if (flag) {
            if (0 != mapper.checkCode(entity.getCode(), entity.getOrgId1(), entity.getId()).size()) {
                throw new LogicException("编码已存在");
            }
        } else if (0 != mapper.checkCode(entity.getCode(), entity.getOrgId1(), "").size()) {
            throw new LogicException("编码已存在");
        }

    }

    /**
     * 校验name
     *
     * @param entity 仓库
     * @param flag   新增/修改
     */
    private void checkName(Category entity, Boolean flag) {
        if (flag) {
            if (0 != mapper.checkName(entity.getName(), entity.getOrgId1(), entity.getId()).size()) {
                throw new LogicException("名称已存在");
            }
        } else if (0 != mapper.checkName(entity.getName(), entity.getOrgId1(), "").size()) {
            throw new LogicException("名称已存在");
        }

    }

    /**
     * 删仓库授权
     *
     * @param entity 仓库
     */
    private void delCategoryAuth(Category entity) {
        Example exampleAuth = new Example(UserDateAuth.class);
        Example.Criteria criteriaAuth = exampleAuth.createCriteria();
        criteriaAuth.andEqualTo("authId", entity.getId());
        criteriaAuth.andEqualTo("type", 4);
        userDateAuthMapper.deleteByExample(exampleAuth);
    }
    /*****************************************************************************************************************************************/

    /**
     * 新增
     *
     * @param entity 仓库
     * @return Category
     */
    public Category add(Category entity) {
        entity.setIsCheck(2);
        //code唯一
        checkCode(entity, false);
        //name唯一
        checkName(entity, false);
        mapper.insertSelective(entity);
        return entity;
    }

    /**
     * 修改
     *
     * @param entity 仓库
     * @return Category
     */
    public Category edit(Category entity) {
        //code唯一
        checkCode(entity, true);
        //name唯一
        checkName(entity, true);
        mapper.updateByPrimaryKeySelective(entity);
        return entity;
    }

    /**
     * 删除（禁用/启用）
     *
     * @param entity 仓库id、修改后状态
     * @return Category
     */
    public Category del(Category entity) {
        Category category = mapper.selectByPrimaryKey(entity.getId());
        //有子类型不能删除
        Example exampleCategory = new Example(CategoryProduct.class);
        Example.Criteria criteriaCategory = exampleCategory.createCriteria();
        criteriaCategory.andEqualTo("categoryId", entity.getId());
        criteriaCategory.andNotEqualTo("productNum", 0);
        List<CategoryProduct> categoryProductList = categoryProductMapper.selectByExample(exampleCategory);
        //校验是否能删除
        if (entity.getState() == 3 && categoryProductList.size() != 0) {
            throw new LogicException("仓库下有物品不能删除");
        }
        Example example = new Example(UserDateAuth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("type", 4);
        criteria.andEqualTo("authId", entity.getId());
        List<UserDateAuth> userDateAuths = userDateAuthMapper.selectByExample(example);
        if (entity.getState() == 3 && userDateAuths.size() != 0) {
            throw new LogicException("仓库已授权不能删除");
        }
        if (entity.getState() == 3) {
            delCategoryAuth(entity);
        }
        entity.setState(entity.getState());
        mapper.updateByPrimaryKeySelective(entity);
        return entity;
    }

    /**
     * 查看
     *
     * @param entity 仓库id
     * @return Category
     */
    public Category view(Category entity) {
        Category category = mapper.selectByPrimaryKey(entity.getId());
        category.setOrgName(orgMapper.selectByPrimaryKey(category.getOrgId()).getName());
        return category;
    }

    /**
     * 查询机构下可用仓库
     *
     * @param orgId 机构id
     * @return List<Category>
     */
    public List<Category> getAvailableCategoryByOrgId(String orgId) {
        return mapper.getPagesNew(orgId);
    }

    /**
     * 查询用户权限下可用仓库
     *
     * @param userId 用户id
     * @return List<Category>
     */
    public List<Category> getAvailableCategoryByUserId(String userId, String orgId) {
        Example example = new Example(UserDateAuth.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        List<UserDateAuth> userDateAuths = userDateAuthMapper.selectByExample(example);
        List<Category> categoryList = new ArrayList<>();
        if (userDateAuths.size() == 0) {
            return mapper.getPagesNew(orgId);
        }
        for (UserDateAuth userDateAuth : userDateAuths) {
            if (userDateAuth.getType() == 4) {
                Category category = mapper.selectByPrimaryKey(userDateAuth.getAuthId());
                if (category.getState() == 1) {
                    categoryList.add(category);
                }
            }
        }
        return categoryList;
    }

    public List<Category> getAllCategory(String companyId) {
        Example example = new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", companyId);
        criteria.andNotEqualTo("state", 3);
//        List<Category> categoryList = mapper.selectByExample(example);
        List<Category> categoryList = mapper.getPages(companyId);
        for (Category category : categoryList) {
            category.setOrgName(orgMapper.selectByPrimaryKey(category.getOrgId()).getName());
            if (category.getState() == 1) {
                category.setState1("可用");
            }
            if (category.getState() == 2) {
                category.setState1("禁用");
            }
        }
        return categoryList;
    }

    public List<Category> getPages(PageParams<Category> params) {
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        return mapper.getPages(params.getParams().getOrgId());
    }

    /**
     * 即时库存查询
     *
     * @param params
     * @return
     */
    public List<ReceiptStock> getStockList(PageParams<StockParams> params) {
        String userId = params.getParams().getUserid();
        //权限
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            params.getParams().setIfadmin(2);
        } else {
            params.getParams().setIfadmin(1);
        }
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptStock> pageList = mapper.getStockList(params.getParams());
        return pageList;
    }

    /**
     * 即时库存导出
     *
     * @param params
     * @return
     */
    public List<ReceiptStock> Export(StockParams params) {
        String userId = params.getUserid();
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            params.setIfadmin(2);
        } else {
            params.setIfadmin(1);
        }
        List<ReceiptStock> pageList = mapper.getStockList(params);
        return pageList;
    }


    /**
     * 耗材领用查询导出
     */
    public List<ReceiptMables> MablExport(MablesParams params) {
        String userId = params.getUserid();
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            params.setIfadmin(2);
        } else {
            params.setIfadmin(1);
        }
        List<ReceiptMables> pageList = mapper.getMablesList(params);
        for (ReceiptMables receiptMables : pageList) {
            String id = receiptMables.getId();
            String startdate = params.getStartdate();
            String enddate = params.getEnddate();
            List<ReceiptCon> receiptConList = mapper.MablesList(id,startdate,enddate);
            Integer outNum = 0;
            float outTotalPrice = (float) 0.00;
            for (ReceiptCon receiptCon : receiptConList) {
                outNum += receiptCon.getLynum();//物品数量求和
                outTotalPrice += Float.parseFloat(receiptCon.getPrice());//物品金额求和
            }
            receiptMables.setReceiptConList(receiptConList);
            receiptMables.setLynum(outNum);
            receiptMables.setPrice(String.valueOf(outTotalPrice));
        }
        return pageList;
    }


    /**
     * 耗材领用查询
     *
     * @param params
     * @return
     */
    public List<ReceiptMables> getMablesList(PageParams<MablesParams> params) {
        String userId = params.getParams().getUserid();
        //权限
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            params.getParams().setIfadmin(2);
        } else {
            params.getParams().setIfadmin(1);
        }
        //权限结束
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptMables> pageList = mapper.getMablesList(params.getParams());
        for (ReceiptMables receiptMables : pageList) {
            String id = receiptMables.getId();
            String startdate = params.getParams().getStartdate();
            String enddate = params.getParams().getEnddate();
            List<ReceiptCon> receiptConList = mapper.MablesList(id,startdate,enddate);
            Integer outNum = 0;
            float outTotalPrice = (float) 0.00;
            for (ReceiptCon receiptCon : receiptConList) {
                outNum += receiptCon.getLynum();//物品数量求和
                outTotalPrice += Float.parseFloat(receiptCon.getPrice());//物品金额求和
            }
            DecimalFormat decimalFormat = new DecimalFormat(".00");
            String p = decimalFormat.format(outTotalPrice);
            receiptMables.setReceiptConList(receiptConList);
            receiptMables.setLynum(outNum);
            receiptMables.setPrice(p);
        }
        return pageList;
    }

    /**
     * 耗材领用表
     *
     * @param params
     * @return
     */
    public List<ReceiptConsume> getConsumeList(PageParams<ConsumeParams> params) {
        String userId = params.getParams().getUserid();
        //权限
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            params.getParams().setIfadmin(2);
        } else {
            params.getParams().setIfadmin(1);
        }
        //权限结束
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<ReceiptConsume> pageList = mapper.getConsumeList(params.getParams());
        for (ReceiptConsume receiptConsume : pageList) {
            String id = receiptConsume.getId();
            String year = receiptConsume.getYear();
            //3个list传参
            List<ReceiptConsum> numList = mapper.getNumlist(id, year);
            List<ReceiptConsum> pricelist = mapper.getPricelist(id, year);
            List<ReceiptConsum> tpricelist = mapper.getTpricelist(id, year);
            //进行数量统计
            Integer outNum = 0;
            float outTotalPrice = (float) 0.00;
            float TotalPrice = (float) 0.00;

            for (ReceiptConsum receiptConsum : numList) {
                outNum += receiptConsum.getLynum();//物品数量求和
            }
            for (ReceiptConsum receiptConsum : tpricelist) {
                outTotalPrice += Float.parseFloat(receiptConsum.getAmount());//物品金额求和
            }
            for (ReceiptConsum receiptConsum : pricelist) {
                TotalPrice += Float.parseFloat(receiptConsum.getAmount());
                //求物品单价平均值
            }
            TotalPrice = TotalPrice / numList.size(); //求物品单价平均值
            receiptConsume.setNumlist(numList);
            receiptConsume.setPricelist(pricelist);
            receiptConsume.setTpricelist(tpricelist);
            receiptConsume.setNumtotal(outNum);
            receiptConsume.setPricetotal(String.valueOf(outTotalPrice));
            receiptConsume.setTpricetotal(String.valueOf(TotalPrice));
        }
        return pageList;
    }

    /**
     * 耗材领用打印
     *
     * @param
     * @return
     */
    public ReceiptMables MablPrint(MablesParams Params) {
        String userId = Params.getUserid();
        ReceiptUser receiptUser = mapper.getAdmin(userId);
        if ((receiptUser.getType().equals("1")) && receiptUser.getDia() == 1) {
            Params.setIfadmin(2);
        } else {
            Params.setIfadmin(1);
        }
        List<ReceiptMables> pageList = mapper.getMablesList(Params);
        for (ReceiptMables receiptMables : pageList) {
            String id = receiptMables.getId();
            String startdate = Params.getStartdate();
            String enddate = Params.getEnddate();
            List<ReceiptCon> receiptConList = mapper.MablesList(id,startdate,enddate);
            Integer outNum = 0;
            float outTotalPrice = (float) 0.00;
            for (ReceiptCon receiptCon : receiptConList) {
                outNum += receiptCon.getLynum();//物品数量求和
                outTotalPrice += Float.parseFloat(receiptCon.getPrice());//物品金额求和
            }
            receiptMables.setReceiptConList(receiptConList);
            receiptMables.setLynum(outNum);
            receiptMables.setPrice(String.valueOf(outTotalPrice));
        }
        return (ReceiptMables) pageList;
    }
}
